package board;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import model.*;
import community.*;

import org.apache.struts.action.*;
import org.apache.struts.actions.*;

import util.*;

public class DataBoardAction extends DispatchAction {	
	
	private String saveFilePath;
	
	//특정 자료실 목록 보기
	public ActionForward getList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		DataForm dataForm = (DataForm)form;
		
		int cono = 0;
		String dbname = null;
		
		System.out.println("dbname= "+ dataForm.getDbname());
		System.out.println("cono= "+ dataForm.getCono());		
		
		if(dataForm.getCono()!=0){
			cono = Integer.parseInt(request.getParameter("cono"));
			dataForm.setCono(cono);
		}else{
			cono = dataForm.getCono();
		}
		
		if(cono<10)	{
			Menu menu = new Menu();
			menu.setDataBoardMenus(this.getDataboardMenus(cono));			
			request.getSession().setAttribute("menu", menu);
		} else {
			CommunityGo.setMemberCommunity(request);
		}
		
		
		if(!dataForm.getDbname().equals("")){
			dbname = URLDecoder.decode(request.getParameter("dbname"),"UTF-8");
			//dbname = request.getParameter("dbname");
			dataForm.setDbname(dbname);
		}else{
			dbname = dataForm.getDbname();
		}
		
		Pager pager = new Pager();
		
		DataBoard dBoard = new DataBoard();
		dBoard.setCono(cono);
		dBoard.setDbname(dbname);
		
		DataBoardDAO dao = new DataBoardDAO();
		int totalRows = dao.getTotalRows(dBoard);
		pager.init(request, totalRows, 10, 5);	
		
		Vector<DataBoard> list = dao.getDataBoardListPage(dBoard, (int)pager.getCurrentPage(), (int)pager.getRowsPerPage());
		
		Vector<DataForm> dataLists = new Vector<DataForm>();		
//		new 표시 시간
		Vector<String> nd = dao.getNewDate();
		
		for(int i=0; i<list.size();i++){
			DataForm df = new DataForm();
						
			df.setRownum(list.get(i).getRownum());
			df.setDbno(list.get(i).getDbno());
			df.setCono(list.get(i).getCono());
			df.setDbname(list.get(i).getDbname());
			df.setMid(list.get(i).getMid());
			df.setDbtitle(list.get(i).getDbtitle());
			df.setDbdate(list.get(i).getDbdate().substring(0,11));
			df.setDbdatetime(list.get(i).getDbdate().substring(0,19));
			df.setDbcontent(list.get(i).getDbcontent());
			df.setDbcounter(list.get(i).getDbcounter());
			df.setOriginalname(list.get(i).getDbofn());
			df.setSavedname(list.get(i).getDbsfn());
			df.setFiletype(list.get(i).getDbftype());
			df.setFileSize(list.get(i).getDbfsize());
			df.setCommentRows(list.get(i).getCommentRows());
			
			for(int j=0; j<nd.size();j++){
				String s = new String();
				s=nd.get(j);
				if(s.equals(df.getDbdatetime())){
					df.setDdd(s);
				}
			}
						
			String nick = MemberCommunityDAO.getCommunityNick(list.get(i).getMid(), list.get(i).getCono());
			df.setNick(nick!=null?nick:list.get(i).getMid());		
			
			dataLists.add(df);			
		}	
		
		dataForm.setDataLists(dataLists);
		dataForm.setCono(dBoard.getCono());
		dataForm.setDbname(dBoard.getDbname());	
		
		request.setAttribute("pager", pager);
		request.setAttribute("dataForm", dataForm);
				
		return mapping.findForward("datalist");
	}	
	
	//자료실 특정 게시물 목록 불러오기
	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {		
		DataForm dataForm = (DataForm)form;	
		
		Pager pager = new Pager();
		DataBoard board = new DataBoard();
		DataBoardDAO dao = new DataBoardDAO();
		
		int cono = 0;
		String dbname = null;		
		//cono, dbname 세팅
		if(dataForm.getCono()!=0){
			cono = Integer.parseInt(request.getParameter("cono"));
			dataForm.setCono(cono);
		}else{
			cono = dataForm.getCono();
		}
		if(!dataForm.getDbname().equals("")){
			dbname = URLDecoder.decode(request.getParameter("dbname"),"UTF-8");
			dataForm.setDbname(dbname);
		}else{
			dbname = dataForm.getDbname();
		}
		
		
		
		int totalRows = 0;
		String data = request.getParameter("data");
		String searchValue = dataForm.getSearchData();
		System.out.println("searchValue= "+searchValue);
		String value =null;
		if(searchValue==null){
			value = (String)request.getSession().getAttribute("keyword");
			System.out.println("value="+value);
		}else{
			value = searchValue;
			request.getSession().setAttribute("keyword", searchValue);
		}
		System.out.println("DATA= "+data);
		System.out.println("dataForm.getSearchList= "+dataForm.getSearchList());
		
		if(dataForm.getSearchList()!=null||data.equals("mid")||data.equals("dbtitle")){
			System.out.println("DATADATA= "+ data);
			if(dataForm.getSearchList()==null){
				if(data.equals("mid")){
					dataForm.setSearchList("mid");
				}else if(data.equals("dbtitle")){
					dataForm.setSearchList("dbtitle");
				}				
			}
			//글쓴이로 검색했을 경우 닉넴을 아이디로 변경		
			if(dataForm.getSearchList().equals("mid")||data=="mid"){
				String id = MemberCommunityDAO.getCommunityMid(value, cono);			
				System.out.println("MID " +data);
				board.setCono(cono);
				board.setDbname(dbname);		
				board.setSearchList(dataForm.getSearchList());
				board.setSearchData(id);
				
				totalRows = dao.getTotalRowsByMid(id, cono, dbname);
				pager.init(request, totalRows, 10, 5);
				dataForm.setSearchList("mid");				
								
				
			//제목으로 검색했을 경우 
			}else if(dataForm.getSearchList().equals("dbtitle")||data=="dbtitle"){
				System.out.println("TITLE "+data);
				board.setCono(cono);
				board.setDbname(dbname);		
				board.setSearchList(dataForm.getSearchList());
				board.setSearchData(value);
				System.out.println("%%%%%%%"+value);
				
				totalRows = dao.getTotalRowsByTitle(value, cono, dbname);
				pager.init(request, totalRows, 10, 5);
				dataForm.setSearchList("dbtitle");
								
			}
		}			
		
		Vector<DataBoard> list = dao.search(board,(int)pager.getCurrentPage(),(int)pager.getRowsPerPage());		
		Vector<DataForm> dataLists = new Vector<DataForm>();		
		for(int i=0; i<list.size();i++){
			DataForm df = new DataForm();
			df.setRownum(list.get(i).getRownum());
			df.setDbno(list.get(i).getDbno());
			df.setCono(list.get(i).getCono());
			df.setDbname(list.get(i).getDbname());
			df.setMid(list.get(i).getMid());
			df.setDbtitle(list.get(i).getDbtitle());
			df.setDbdate(list.get(i).getDbdate().substring(0,11));
			df.setDbcontent(list.get(i).getDbcontent());
			df.setDbcounter(list.get(i).getDbcounter());
			df.setOriginalname(list.get(i).getDbofn());
			df.setSavedname(list.get(i).getDbsfn());
			df.setFiletype(list.get(i).getDbftype());
			df.setFileSize(list.get(i).getDbfsize());
			df.setCommentRows(list.get(i).getCommentRows());
			
			String nick = MemberCommunityDAO.getCommunityNick(list.get(i).getMid(), list.get(i).getCono());
			df.setNick(nick!=null?nick:list.get(i).getMid());
			
			dataLists.add(df);
		}
		
		dataForm.setDataLists(dataLists);
		dataForm.setCono(board.getCono());
		dataForm.setDbname(board.getDbname());
		
		request.setAttribute("pager", pager);
	
		return mapping.findForward("datalist");	
	}
	
	//자료실 글쓰기 폼 불러오기
	public ActionForward getForm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		DataForm df = (DataForm)form;
		User user = (User)request.getSession().getAttribute("user");
		String mid = user.getMid();
				
		String nick = MemberCommunityDAO.getCommunityNick(user.getMid(), df.getCono());
		
		
		df.setNick(nick);		
		df.setMid(mid);

		return mapping.findForward("datainsert");
	}
	
	//자료실 글쓰기
	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {		
		DataForm df = (DataForm)form;		
		
		DataBoard db = new DataBoard();
		DataBoardDAO dao = new DataBoardDAO();
		
		System.out.println("cono: "+df.getCono());
		System.out.println("dnname: "+df.getDbname());
		
		db.setCono(df.getCono());
		db.setDbname(df.getDbname());
		db.setDbtitle(df.getDbtitle());
		db.setDbcontent(df.getDbcontent());
		
		String originalName = df.getFile().getFileName();
		String savedName = null;
		String fileType = null;
		int fileSize = 0;
		
		if(originalName.equals("")){
			originalName = null;
		}else{
			fileType = df.getFile().getContentType();
			fileSize = df.getFile().getFileSize();
			
			ServletContext sc = request.getSession().getServletContext();			
			String fileName = sc.getRealPath("/uploadfiles/"+originalName); 
			InputStream is = df.getFile().getInputStream();
			savedName = FileSaver.save(fileName, is);
			savedName = savedName.substring(savedName.lastIndexOf("\\")+1);
		}	
		
		User user = (User)request.getSession().getAttribute("user");
		
		db.setMid(user.getMid());		
		db.setDbofn(originalName);
		db.setDbsfn(savedName);
		db.setDbftype(fileType);
		db.setDbfsize(fileSize);
		boolean result = dao.insert(db);
		
		if(result){
			return getList(mapping, form, request, response);
		}else{
			return mapping.findForward("datainsert");
		}
		
//		ActionForward af = new ActionForward();
//		af.setPath("/databoard.do?method=getAllList");
//		af.setRedirect(true);
//		return af;
	}	
	
	//자료실 글 읽기
	public ActionForward detailview(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {		
		DataForm dataForm = (DataForm)form;
		User user = (User)request.getSession().getAttribute("user");
		
		DataBoard board = new DataBoard();		
		DataComment dc = new DataComment();		
		DataBoardDAO dao = new DataBoardDAO();	
		DataForm preForm = new DataForm();
		DataForm nextForm = new DataForm();
		
		int rowNum = dataForm.getRownum();
		
		board.setDbno(dataForm.getDbno());
		DataBoard db = dao.getDataBoard(board.getDbno());
		
		int preNum = dao.getPreNum(db);
		int nextNum = dao.getNextNum(db);		
		
		
		//조회수 증가시키기		
		if(!(user.getMid()).equals(db.getMid())){
			dao.incrementCounter(db);
		}
		//이전글 불러오기
		if(preNum<db.getDbno()){
			DataBoard dBoard = dao.getDataBoard(preNum);
			
			DataForm df = castBoardToForm(preForm, dBoard);
			df.setRownum(rowNum-1);
			
			dataForm.setPreview(df);
		}else{
			dataForm.setPreview(null);
		}
		//다음글 불러오기
		if(nextNum>db.getDbno()){
			DataBoard dBoard = dao.getDataBoard(nextNum);
			
			DataForm df = castBoardToForm(nextForm, dBoard);
			df.setRownum(rowNum+1);
			
			dataForm.setNext(df);
		}else{
			dataForm.setNext(null);
		}					
		
		/////글 내용 /////////////////////////////
		castBoardToForm(dataForm, db);			
		
//		특정 글의 꼬리말 불러오기 글의 번호 세팅
		dc.setDbno(dataForm.getDbno());
		dataForm.setRownum(rowNum);
        //꼬리말 불러오기
//		DataCommentAction ca = new DataCommentAction();
//		dataForm.setCommentList(ca.commentList(dc,dataForm.getCono()));		
		/////////////////////////////////////////		
		//request.setAttribute("dataForm", dataForm);

		ActionForward af = new ActionForward();
		af.setPath("/dataview.jsp");
		return af;
	}
	
	//dto를 actionform으로 cast
	public DataForm castBoardToForm(DataForm form, DataBoard board){
		
		form.setDbno(board.getDbno());
		form.setCono(board.getCono());
		form.setMid(board.getMid());
		form.setDbtitle(board.getDbtitle());
		form.setDbcontent(board.getDbcontent());
		form.setDbdate(board.getDbdate());
		form.setDbcounter(board.getDbcounter());
		form.setOriginalname(board.getDbofn());
		form.setSavedname(board.getDbsfn());
		form.setFiletype(board.getDbftype());
		form.setFileSize(board.getDbfsize());
		form.setDbname(board.getDbname());
		
		String nick = MemberCommunityDAO.getCommunityNick(board.getMid(), board.getCono());
		if(nick!=null){
			form.setNick(nick);
		}else{
			form.setNick(board.getMid());
		}
		return form;
	}
	
	
	//자료실 글 수정 폼 불러오기
	public ActionForward getModifyForm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		DataForm dataForm = (DataForm)form;
	
		DataBoard board = new DataBoard();
		DataBoardDAO dao = new DataBoardDAO();
		
		board.setDbno(dataForm.getDbno());
		DataBoard db = dao.getDataBoard(board.getDbno());
		
		dataForm.setDbno(db.getDbno());
		dataForm.setDbtitle(db.getDbtitle());
		dataForm.setDbcontent(db.getDbcontent());
		dataForm.setOriginalname(db.getDbofn());
		dataForm.setSavedname(db.getDbsfn());
		dataForm.setFiletype(db.getDbftype());
					
		return mapping.findForward("dataupdate");
	}
	
	//자료실 글 수정하기
	public ActionForward modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		DataForm dataForm = (DataForm)form;
		DataBoard board = new DataBoard();
		DataBoardDAO dao = new DataBoardDAO();
		
		board.setDbno(dataForm.getDbno());
		board.setDbtitle(dataForm.getDbtitle());
		board.setDbcontent(dataForm.getDbcontent());
		board.setCono(dataForm.getCono());
		board.setDbname(dataForm.getDbname());
		
		System.out.println("cono = "+board.getCono());
		System.out.println("dbname = "+board.getDbname());
		
		String originalName = dataForm.getFile().getFileName();
		String savedName = null;
		String fileType = null;
		int fileSize = 0;
		
		if(originalName.equals("")){
			originalName = null;
		}else{
			fileType = dataForm.getFile().getContentType();
			fileSize = dataForm.getFile().getFileSize();
			ServletContext sc = request.getSession().getServletContext();
			String filename = sc.getRealPath("/uploadfiles/"+originalName);
			
			InputStream is = dataForm.getFile().getInputStream();
			savedName = FileSaver.save(filename, is);
			savedName = savedName.substring(savedName.lastIndexOf("\\")+1);
		}
		//파일명, 타입을 DTO에 세팅
		board.setDbofn(originalName);
		board.setDbsfn(savedName);
		board.setDbfsize(fileSize);
		board.setDbftype(fileType);
		
		//기존의 저장된 파일이 있을 경우 기존 파일을 지우고 자료를 올림
		if(originalName!=null){
			DataBoard db = dao.getDataBoard(board.getDbno());
			if(db.getDbofn()!=null){
				ServletContext sc = request.getSession().getServletContext();
				saveFilePath = sc.getRealPath("/uploadfiles")+"/"+db.getDbsfn();		
				File file = new File(saveFilePath);	
				file.delete();
			}
			db.setDbofn(originalName);
			db.setDbsfn(savedName);
			db.setDbfsize(fileSize);
			db.setDbftype(fileType);
			
			dao.updateContent(board);			
			dao.updateFile(db);
		}else{			
			dao.updateContent(board);		
			dao.updateFile(board);
		}		
		
		ActionForward af = new ActionForward();
		af.setPath("/databoard.do?method=detailview&dbno="+dataForm.getDbno());
		af.setRedirect(true);
		return af;
	}
	
	//자료실 글 삭제하기
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		DataForm dataForm = (DataForm)form;
		int dbno = dataForm.getDbno();
		DataBoard board = new DataBoard();
		DataBoardDAO dao = new DataBoardDAO();
		DataCommentDAO coDao = new DataCommentDAO();		
		
		board.setDbno(dbno);
		DataBoard db = dao.getDataBoard(board.getDbno());
		//파일이 있을 경우 파일부터 삭제
		if(db.getDbsfn()!=null){
			ServletContext sc = request.getSession().getServletContext();
			saveFilePath = sc.getRealPath("/uploadfiles")+"/"+db.getDbsfn();		
			File file = new File(saveFilePath);
			boolean fileremoved = file.delete();
			
			if(fileremoved){
				//꼬리말이 있으면 꼬리말부터 삭제
				if(db.getCommentRows()!=0){
					boolean complete = coDao.deleteForData(dbno);
					if(complete){
						dao.delete(board);
					}
				}else{
					dao.delete(board);
				}				
			}
		//파일이 없는 경우
		}else{
			if(db.getCommentRows()!=0){
				boolean complete = coDao.deleteForData(dbno);
				if(complete){
					dao.delete(board);
				}
			}else{
				dao.delete(board);
			}			
		}					
		
		return getList(mapping, dataForm, request, response);

	}	
	
	//자료실 자료 다운로드 하기
	public ActionForward download(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String dbno = request.getParameter("dbno");		
		if(dbno!=null){
			readDataBoardTable(request, response, dbno);
		}
		return null;
	}
	
	//다운로드 할 파일 읽기
	public void readDataBoardTable(HttpServletRequest request, HttpServletResponse response, String dbno){
		Connection conn = null;
		try {
			//테이블에서 파일의 원래 이름, 파일의 저장이름, 파일 타입 얻기
			conn = ConnectionManager.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt
					.executeQuery("select dbofn, dbsfn, dbftype, dbfsize from databoard where dbno="
							+ dbno);	
			if (rs.next()) {
				String originalName = rs.getString("dbofn");
				String savedName = rs.getString("dbsfn");
				String fileType = rs.getString("dbftype");
				int fileSize = rs.getInt("dbfsize");
				
				//클라이언트로 파일 내용 보내기
				sendFile(request, response, originalName, savedName, fileType);
			}
			rs.close();
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	//클라이언트로 파일 보내기
	private void sendFile(HttpServletRequest request, HttpServletResponse response, String originalName,
			String savedName, String fileType) {
		//클라이언트가 파일을 다운로드해야 함을 응답 HTTP 헤더에 세팅		
		try {
			//Http헤더에는 한글이 포함될 수 없기 때문에 8859_1로 인코딩해야함
			originalName = new String(originalName.getBytes("euc-kr"),"8859_1");
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		}
		response.setHeader("Content-Disposition", "attachment;filename="+originalName);
		
		//파일의 타입을 응답 HTTp 헤더에 세팅
		response.setContentType(fileType);
		if(saveFilePath==null){
			ServletContext sc = request.getSession().getServletContext();
			saveFilePath = sc.getRealPath("/uploadfiles");
		}
		
		System.out.println(saveFilePath);
		
		//파일 데이터를 응답 Http 바디에 포함
		try {
			//응답 Http바디로 출력하는 출력 스트림 얻기(바이너리 스트림)
			ServletOutputStream sos = response.getOutputStream();
			//파일로부터 데이터를 읽는 입력스트림 얻기(바이너리 스트림)
			FileInputStream fis = new FileInputStream(saveFilePath+"/"+savedName);
			//파일의 데이터를 읽고 출력하기
			byte[] datas = new byte[1024];
			int n = -1;
			while((n=fis.read(datas,0,1024))!=-1){
				sos.write(datas,0,n);
			}
			fis.close();
			sos.close();
			
		} catch (IOException e) {		
			e.printStackTrace();
		}
		
	}	
	
	//메인  자료실 메뉴 세팅하기
	public ActionForward setMenus(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Menu menu = new Menu();	
		
		if(request.getSession().getAttribute("membercommunity")!=null) request.getSession().setAttribute("membercommunity", null);
		
		menu.setDataBoardMenus(this.getDataboardMenus(7));
		
		request.getSession().setAttribute("menu", menu);
		
		ActionForward af = new ActionForward();
		af.setPath("/datamain.jsp");
		af.setRedirect(true);
		
		return af;
	}
	
	//특정 커뮤니티의 자료실 메뉴 정보 가져오기
	 public static Vector getDataboardMenus(int cono) {
		 
		  Vector<BoardNames> v = new Vector<BoardNames>();
		  
		  String url = "databoard.do?method=getList&cono="+cono+"&dbname=";
		  
		  DataBoardDAO dao = new DataBoardDAO();
		  String[] bnames = dao.getBoardMenus(cono);		  
		  
		  for(int i=0;i<bnames.length;i++){
		   BoardNames bns = new BoardNames();
		   bns.setBname(bnames[i]);
		   bns.setUrl(url);
		   v.add(bns);
		  }  
		  return v;
	}



}
